package com.basejace.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.basejace.common.model.PubAuthority;
import com.basejace.core.base.BaseController;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

public class AuthorityController extends BaseController {

	public AuthorityController() {
		setModelClass(PubAuthority.class);
	}
	
	public void show() {
		setAttr("roleid", getPara("roleid"));
		render("tree.jsp");
	}
	
	@Before(Tx.class)
	public void reset(){
		Long roleid = getParaToLong("roleid");
		String controlids = getPara("controlids");
		
		if (roleid == null) {
			setAttr("roleid", getPara("roleid"));
			render("tree.jsp");
			return ;
		}
		
		try {
			//
			Db.update("delete from pub_authority where objectid=? and objecttype=?", new Object[]{roleid, "1"});
			String [] controlidArray = controlids.split(",");
			for (String controlid : controlidArray) {
				PubAuthority entity = new PubAuthority();
				entity.setControlid(controlid)
					.setObjectid(roleid)
					.setObjecttype("1") //这里是角色
					.setCtime(new Date())
					.setState("1")
					.save();
			}
			
		} catch(Exception ex) {
			ex.printStackTrace();
			setAttr(MSG, "设置失败" + ex.getMessage());
		}
		
		
		setAttr(MSG, "设置成功");
		setAttr("roleid", getPara("roleid"));
		render("tree.jsp");
	}
	
	//获取对象所有的 控制点列表
	public void getContorlids() {
		String objectid = getPara("objectid");
		Integer objecttype = getParaToInt("objecttype");
		
//		String rolename = getPara("rolename");
		String sqlExceptSelect = "select * from pub_authority where 1=1 ";
		List sqlCondition = new ArrayList();
		if (StrKit.notBlank(objectid)) {
			sqlExceptSelect += "and objectid = ? ";
			sqlCondition.add(objectid);
		}
		if (objecttype != null) {
			sqlExceptSelect += "and objecttype = ? ";
			sqlCondition.add(objecttype);
		}
		
		sqlExceptSelect += " order by controlid";
//		int offset = getParaToInt("offset");
//		int limit = getParaToInt("limit");
//		int pageNumber = (offset) / limit + 1;
//		
//		Page<Record> page = Db.paginate(pageNumber, limit, "select * ", sqlExceptSelect , sqlCondition.toArray());
		JSONArray arr = new JSONArray();
		try {
			List<PubAuthority> list = getModelEntity().dao().find(sqlExceptSelect, sqlCondition.toArray());
			
			for (Iterator<PubAuthority> iterator = list.iterator(); iterator.hasNext();) {
				PubAuthority authority = iterator.next();
				arr.add(authority.getControlid());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		log.info(arr.toJSONString());
		renderJson(arr);
	}
	
	public void beforeSave() throws Exception {
		//this.getModelEntity().set("roleid", Sequence.getSequence());
	}
}
